package com.masonluo.mlonlinejudge.config;


import com.masonluo.mlonlinejudge.entity.User;
import com.masonluo.mlonlinejudge.service.UserService;
import com.masonluo.mlonlinejudge.utils.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.masonluo.mlonlinejudge.dao.*;

import javax.annotation.Resource;
import java.util.*;


public class UserRealm extends AuthorizingRealm {

    @Resource
    UserRepository userRepository;

    @Resource
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        User user=(User)principalCollection.getPrimaryPrincipal();
        String username=user.getUsername();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //给admin设置角色(应该从数据库表中获取)
        String roleName=userService.getUserRolesByUsername(username);
        authorizationInfo.addRole(roleName);
        //给用户设置权限
//        authorizationInfo.setStringPermissions();
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username=(String)token.getPrincipal();
        String password = new String(token.getPassword());
        List<User> user = userRepository.selectByUsernameAndPassword(username,password);
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || user.isEmpty()) {
            throw new IllegalArgumentException("账号或密码错误");
        }
        for (User user1:user) {
            if(username.equals(user1.getUsername())){
                return new SimpleAuthenticationInfo(user1, user1.getPassword(),this.getName());
            }
        }
        return null;
    }
}
